<template>
  <div class="system-message">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>消息通知</el-breadcrumb-item>
      <el-breadcrumb-item>系统消息</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- WebSocket连接状态指示器 -->
    <div class="ws-status-indicator">
      <el-tooltip :content="wsConnected ? '实时系统消息已连接' : '实时系统消息连接已断开'" placement="bottom">
        <div :class="['status-dot', wsConnected ? 'connected' : 'disconnected']">
          <span class="status-text">{{ wsConnected ? '系统实时' : '系统断开' }}</span>
        </div>
      </el-tooltip>
    </div>

    <!-- 统计信息卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #409eff;">
              <el-icon><Message /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalMessages || 0 }}</div>
              <div class="stat-label">总消息数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #67c23a;">
              <el-icon><SuccessFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.sentMessages || 0 }}</div>
              <div class="stat-label">已发送</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.pendingMessages || 0 }}</div>
              <div class="stat-label">待发送</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <el-icon><WarningFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.failedMessages || 0 }}</div>
              <div class="stat-label">发送失败</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="left-buttons">
          <el-button type="primary" icon="Plus" @click="showSendMessageDialog">
            发送消息
          </el-button>
          <el-button type="success" icon="Promotion" @click="showBroadcastDialog">
            广播消息
          </el-button>
          <el-button type="warning" icon="Refresh" @click="handleRefresh">
            刷新
          </el-button>
        </div>
        <div class="right-buttons">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="!selectedMessages.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <el-button
            type="info"
            icon="Download"
            @click="handleExport"
          >
            导出
          </el-button>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" ref="searchFormRef">
          <el-form-item label="消息标题" prop="title">
            <el-input
              v-model="searchForm.title"
              placeholder="请输入消息标题"
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="消息类型" prop="messageType">
            <el-select
              v-model="searchForm.messageType"
              placeholder="请选择消息类型"
              clearable
              style="width: 150px;"
            >
              <el-option label="通知" value="notification" />
              <el-option label="公告" value="announcement" />
              <el-option label="提醒" value="reminder" />
              <el-option label="警告" value="warning" />
            </el-select>
          </el-form-item>
          <el-form-item label="发送状态" prop="status">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择发送状态"
              clearable
              style="width: 150px;"
            >
              <el-option label="已发送" value="sent" />
              <el-option label="待发送" value="pending" />
              <el-option label="发送失败" value="failed" />
            </el-select>
          </el-form-item>
          <el-form-item label="发送时间" prop="dateRange">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="handleResetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 消息列表表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="messageList"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="title" label="消息标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="messageType" label="消息类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getMessageTypeTagType(row.messageType)">
              {{ getMessageTypeLabel(row.messageType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="senderName" label="发送者" width="120" />
        <el-table-column prop="targetType" label="接收对象" width="120">
          <template #default="{ row }">
            <span>{{ getTargetTypeLabel(row.targetType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="recipientCount" label="接收人数" width="100" />
        <el-table-column prop="status" label="发送状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTagType(row.priority)" size="small">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sendTime" label="发送时间" width="180" />
        <el-table-column prop="createAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="View"
              @click="handleViewMessage(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="handleEditMessage(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="handleDeleteMessage(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发送消息对话框 -->
    <el-dialog
      v-model="sendMessageDialogVisible"
      :title="isEdit ? '编辑系统消息' : '发送系统消息'"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        :model="messageForm"
        :rules="messageFormRules"
        ref="messageFormRef"
        label-width="100px"
      >
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="messageForm.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="消息类型" prop="messageType">
          <el-select v-model="messageForm.messageType" placeholder="请选择消息类型" style="width: 100%">
            <el-option label="通知" value="notification" />
            <el-option label="公告" value="announcement" />
            <el-option label="提醒" value="reminder" />
            <el-option label="警告" value="warning" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入消息内容"
          />
        </el-form-item>
        <el-form-item label="接收对象" prop="targetType">
          <el-radio-group v-model="messageForm.targetType" @change="handleTargetTypeChange">
            <el-radio label="all">所有用户</el-radio>
            <el-radio label="role">指定角色</el-radio>
            <el-radio label="user">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="messageForm.targetType === 'role'"
          label="选择角色"
          prop="roleId"
        >
          <el-select v-model="messageForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="1" />
            <el-option label="老师" value="2" />
            <el-option label="学生" value="3" />
            <el-option label="裁判" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="messageForm.targetType === 'user'"
          label="选择用户"
          prop="userIds"
        >
          <el-select
            v-model="messageForm.userIds"
            multiple
            placeholder="请选择用户"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="messageForm.priority">
            <el-radio label="low">低</el-radio>
            <el-radio label="medium">中</el-radio>
            <el-radio label="high">高</el-radio>
            <el-radio label="urgent">紧急</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="定时发送">
          <el-switch v-model="messageForm.isScheduled" />
        </el-form-item>
        <el-form-item
          v-if="messageForm.isScheduled"
          label="发送时间"
          prop="scheduledTime"
        >
          <el-date-picker
            v-model="messageForm.scheduledTime"
            type="datetime"
            placeholder="选择发送时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="sendMessageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSendMessage" :loading="sending">
            {{ isEdit ? '更新' : '发送' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 广播消息对话框 -->
    <el-dialog
      v-model="broadcastDialogVisible"
      title="广播系统消息"
      width="600px"
      @close="handleBroadcastDialogClose"
    >
      <el-form
        :model="broadcastForm"
        :rules="broadcastFormRules"
        ref="broadcastFormRef"
        label-width="100px"
      >
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="broadcastForm.title" placeholder="请输入广播消息标题" />
        </el-form-item>
        <el-form-item label="消息类型" prop="messageType">
          <el-select v-model="broadcastForm.messageType" placeholder="请选择消息类型" style="width: 100%">
            <el-option label="公告" value="announcement" />
            <el-option label="通知" value="notification" />
            <el-option label="紧急通知" value="urgent" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="broadcastForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入广播消息内容"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="broadcastForm.priority">
            <el-radio label="medium">中</el-radio>
            <el-radio label="high">高</el-radio>
            <el-radio label="urgent">紧急</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="broadcastDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBroadcastMessage" :loading="broadcasting">
            立即广播
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="messageDetailDialogVisible"
      title="消息详情"
      width="600px"
    >
      <div class="message-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="消息标题">{{ currentMessage.title }}</el-descriptions-item>
          <el-descriptions-item label="消息类型">
            <el-tag :type="getMessageTypeTagType(currentMessage.messageType)">
              {{ getMessageTypeLabel(currentMessage.messageType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发送者">{{ currentMessage.senderName }}</el-descriptions-item>
          <el-descriptions-item label="接收对象">{{ getTargetTypeLabel(currentMessage.targetType) }}</el-descriptions-item>
          <el-descriptions-item label="接收人数">{{ currentMessage.recipientCount }}</el-descriptions-item>
          <el-descriptions-item label="发送状态">
            <el-tag :type="getStatusTagType(currentMessage.status)">
              {{ getStatusLabel(currentMessage.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTagType(currentMessage.priority)" size="small">
              {{ getPriorityLabel(currentMessage.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentMessage.createAt }}</el-descriptions-item>
          <el-descriptions-item label="发送时间">{{ currentMessage.sendTime || '未发送' }}</el-descriptions-item>
          <el-descriptions-item label="消息内容" :span="2">
            <div class="message-content">{{ currentMessage.content }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
  getSystemMessageList,
  getSystemMessageById,
  sendSystemMessage,
  sendSystemMessageToRole,
  broadcastSystemMessage,
  updateSystemMessage,
  deleteSystemMessage,
  batchDeleteMessages,
  getAdminMessageStatistics
} from '@/api/message'

export default {
  name: 'SystemMessage',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const sending = ref(false)
    const broadcasting = ref(false)
    const messageList = ref([])
    const selectedMessages = ref([])
    const userList = ref([]) // 模拟用户列表

    // WebSocket 实例
    const websocket = ref(null)
    const wsConnected = ref(false)
    const wsReconnectAttempts = ref(0)
    const wsMaxReconnectAttempts = ref(5)
    const wsReconnectInterval = ref(5000)
    const heartbeatTimer = ref(null)

    // 统计数据
    const statistics = reactive({
      totalMessages: 0,
      sentMessages: 0,
      pendingMessages: 0,
      failedMessages: 0
    })

    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    // 搜索表单
    const searchForm = reactive({
      title: '',
      messageType: '',
      status: '',
      dateRange: null
    })

    // 消息表单
    const messageForm = reactive({
      id: null,
      title: '',
      messageType: 'notification',
      content: '',
      targetType: 'all',
      roleId: '',
      userIds: [],
      priority: 'medium',
      isScheduled: false,
      scheduledTime: null
    })

    // 广播表单
    const broadcastForm = reactive({
      title: '',
      messageType: 'announcement',
      content: '',
      priority: 'medium'
    })

    // 当前查看的消息
    const currentMessage = ref({})

    // 对话框显示状态
    const sendMessageDialogVisible = ref(false)
    const broadcastDialogVisible = ref(false)
    const messageDetailDialogVisible = ref(false)
    const isEdit = ref(false)

    // 表单引用
    const searchFormRef = ref(null)
    const messageFormRef = ref(null)
    const broadcastFormRef = ref(null)

    // 表单验证规则
    const messageFormRules = {
      title: [
        { required: true, message: '请输入消息标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      messageType: [
        { required: true, message: '请选择消息类型', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入消息内容', trigger: 'blur' },
        { min: 5, max: 1000, message: '内容长度在 5 到 1000 个字符', trigger: 'blur' }
      ],
      targetType: [
        { required: true, message: '请选择接收对象', trigger: 'change' }
      ],
      roleId: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      userIds: [
        { required: true, message: '请选择用户', trigger: 'change' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      scheduledTime: [
        { required: true, message: '请选择发送时间', trigger: 'change' }
      ]
    }

    const broadcastFormRules = {
      title: [
        { required: true, message: '请输入广播消息标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      messageType: [
        { required: true, message: '请选择消息类型', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入广播消息内容', trigger: 'blur' },
        { min: 5, max: 1000, message: '内容长度在 5 到 1000 个字符', trigger: 'blur' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ]
    }

    // 计算属性
    const hasSelection = computed(() => selectedMessages.value.length > 0)

    // 生命周期钩子
    onMounted(() => {
      loadMessageList()
      loadStatistics()
      loadUserList()
      initWebSocket()
    })

    onBeforeUnmount(() => {
      closeWebSocket()
    })

    // WebSocket 相关方法
    const initWebSocket = () => {
      // 根据当前环境获取WebSocket地址
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const wsUrl = `${protocol}//${window.location.host}/websocket/system-message`

      try {
        websocket.value = new WebSocket(wsUrl)
        setupWebSocketEvents()
      } catch (error) {
        console.error('WebSocket连接失败:', error)
        ElMessage.error('实时系统消息连接失败，将使用定时刷新')
        setupFallbackPolling()
      }
    }

    const setupWebSocketEvents = () => {
      if (!websocket.value) return

      websocket.value.onopen = () => {
        console.log('WebSocket连接成功')
        wsConnected.value = true
        wsReconnectAttempts.value = 0
        startHeartbeat()
        ElMessage.success('实时系统消息已连接')
      }

      websocket.value.onmessage = (event) => {
        handleWebSocketMessage(event)
      }

      websocket.value.onclose = () => {
        console.log('WebSocket连接关闭')
        wsConnected.value = false
        stopHeartbeat()
        handleWebSocketDisconnect()
      }

      websocket.value.onerror = (error) => {
        console.error('WebSocket错误:', error)
        wsConnected.value = false
        ElMessage.warning('实时系统消息连接异常')
      }
    }

    const handleWebSocketMessage = (event) => {
      try {
        const data = JSON.parse(event.data)

        switch (data.type) {
          case 'message_status_update':
            handleMessageStatusUpdate(data.payload)
            break
          case 'new_system_message':
            handleNewSystemMessage(data.payload)
            break
          case 'message_statistics':
            handleMessageStatistics(data.payload)
            break
          case 'heartbeat':
            handleHeartbeatResponse()
            break
          default:
            console.log('未知消息类型:', data.type)
        }
      } catch (error) {
        console.error('处理WebSocket消息失败:', error)
      }
    }

    const handleMessageStatusUpdate = (data) => {
      // 更新消息状态
      const message = messageList.value.find(m => m.id === data.messageId)
      if (message) {
        message.status = data.status
        if (data.sendTime) {
          message.sendTime = data.sendTime
        }
        if (data.recipientCount) {
          message.recipientCount = data.recipientCount
        }
      }

      // 显示通知
      ElNotification({
        title: '系统消息状态更新',
        message: `系统消息"${data.title}"状态已更新为: ${getStatusLabel(data.status)}`,
        type: data.status === 'sent' ? 'success' : data.status === 'failed' ? 'error' : 'warning',
        duration: 5000
      })

      // 更新统计数据
      if (data.statistics) {
        Object.assign(statistics, data.statistics)
      }
    }

    const handleNewSystemMessage = (data) => {
      // 显示新系统消息通知
      ElNotification({
        title: '新的系统消息',
        message: `收到新的系统消息: ${data.title}`,
        type: 'info',
        duration: 8000
      })

      // 刷新消息列表
      loadMessageList()
      loadStatistics()
    }

    const handleMessageStatistics = (data) => {
      // 更新统计数据
      Object.assign(statistics, data)
    }

    const startHeartbeat = () => {
      stopHeartbeat()
      heartbeatTimer.value = setInterval(() => {
        if (websocket.value && wsConnected.value) {
          websocket.value.send(JSON.stringify({ type: 'heartbeat' }))
        }
      }, 30000)
    }

    const stopHeartbeat = () => {
      if (heartbeatTimer.value) {
        clearInterval(heartbeatTimer.value)
        heartbeatTimer.value = null
      }
    }

    const handleHeartbeatResponse = () => {
      console.log('WebSocket心跳正常')
    }

    const handleWebSocketDisconnect = () => {
      // 尝试重连
      if (wsReconnectAttempts.value < wsMaxReconnectAttempts.value) {
        wsReconnectAttempts.value++
        console.log(`WebSocket重连尝试 ${wsReconnectAttempts.value}/${wsMaxReconnectAttempts.value}`)

        setTimeout(() => {
          ElMessage.info(`正在尝试重连(${wsReconnectAttempts.value}/${wsMaxReconnectAttempts.value})...`)
          initWebSocket()
        }, wsReconnectInterval.value)
      } else {
        ElMessage.error('实时系统消息连接失败，已达到最大重连次数，将使用定时刷新')
        setupFallbackPolling()
      }
    }

    const setupFallbackPolling = () => {
      setInterval(() => {
        if (!wsConnected.value) {
          loadMessageList()
          loadStatistics()
        }
      }, 30000)
    }

    const closeWebSocket = () => {
      stopHeartbeat()

      if (websocket.value) {
        websocket.value.close()
        websocket.value = null
      }
      wsConnected.value = false
    }

    // 方法
    const loadMessageList = async () => {
      loading.value = true
      try {
        const params = {
          title: searchForm.title,
          messageType: searchForm.messageType,
          status: searchForm.status,
          startDate: searchForm.dateRange?.[0],
          endDate: searchForm.dateRange?.[1]
        }

        const response = await getSystemMessageList(pagination.currentPage, pagination.pageSize, params)
        if (response.code === 200) {
          messageList.value = response.data.records
          pagination.total = response.data.total
        }
      } catch (error) {
        console.error('加载消息列表失败:', error)
        ElMessage.error('加载消息列表失败')
      } finally {
        loading.value = false
      }
    }

    const loadStatistics = async () => {
      try {
        const response = await getAdminMessageStatistics()
        if (response.code === 200) {
          Object.assign(statistics, response.data)
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    }

    const loadUserList = async () => {
      // 模拟用户数据，实际项目中应该从API获取
      userList.value = [
        { id: 1, username: 'admin', realName: '管理员' },
        { id: 2, username: 'teacher1', realName: '张老师' },
        { id: 3, username: 'student1', realName: '李同学' },
        { id: 4, username: 'referee1', realName: '王裁判' }
      ]
    }

    const handleSearch = () => {
      pagination.currentPage = 1
      loadMessageList()
    }

    const handleResetSearch = () => {
      searchFormRef.value?.resetFields()
      handleSearch()
    }

    const handleRefresh = () => {
      loadMessageList()
      loadStatistics()
    }

    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadMessageList()
    }

    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadMessageList()
    }

    const handleSelectionChange = (selection) => {
      selectedMessages.value = selection
    }

    const showSendMessageDialog = () => {
      isEdit.value = false
      resetMessageForm()
      sendMessageDialogVisible.value = true
    }

    const showBroadcastDialog = () => {
      resetBroadcastForm()
      broadcastDialogVisible.value = true
    }

    const handleDialogClose = () => {
      messageFormRef.value?.resetFields()
      resetMessageForm()
    }

    const handleBroadcastDialogClose = () => {
      broadcastFormRef.value?.resetFields()
      resetBroadcastForm()
    }

    const resetMessageForm = () => {
      Object.assign(messageForm, {
        id: null,
        title: '',
        messageType: 'notification',
        content: '',
        targetType: 'all',
        roleId: '',
        userIds: [],
        priority: 'medium',
        isScheduled: false,
        scheduledTime: null
      })
    }

    const resetBroadcastForm = () => {
      Object.assign(broadcastForm, {
        title: '',
        messageType: 'announcement',
        content: '',
        priority: 'medium'
      })
    }

    const handleTargetTypeChange = (value) => {
      if (value !== 'user') {
        messageForm.userIds = []
      }
      if (value !== 'role') {
        messageForm.roleId = ''
      }
    }

    const handleSendMessage = async () => {
      try {
        await messageFormRef.value.validate()
        sending.value = true

        let response
        if (isEdit.value) {
          // 编辑模式 - 更新消息
          response = await updateSystemMessage(messageForm)
        } else {
          // 新增模式 - 发送消息
          if (messageForm.targetType === 'all') {
            response = await broadcastSystemMessage(messageForm)
          } else if (messageForm.targetType === 'role') {
            response = await sendSystemMessageToRole(messageForm.roleId, messageForm)
          } else if (messageForm.targetType === 'user') {
            // 这里简化处理，实际可能需要遍历用户ID逐个发送或批量发送
            for (const userId of messageForm.userIds) {
              await sendSystemMessage(userId, messageForm)
            }
            response = { code: 200, message: '发送成功' }
          }
        }

        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '发送成功')
          sendMessageDialogVisible.value = false
          loadMessageList()
          loadStatistics()
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新失败' : '发送失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '更新消息失败:' : '发送消息失败:', error)
        ElMessage.error(isEdit.value ? '更新消息失败' : '发送消息失败')
      } finally {
        sending.value = false
      }
    }

    const handleBroadcastMessage = async () => {
      try {
        await broadcastFormRef.value.validate()
        broadcasting.value = true

        const response = await broadcastSystemMessage(broadcastForm)
        if (response.code === 200) {
          ElMessage.success('广播发送成功')
          broadcastDialogVisible.value = false
          loadMessageList()
          loadStatistics()
        } else {
          ElMessage.error(response.message || '广播发送失败')
        }
      } catch (error) {
        console.error('广播消息失败:', error)
        ElMessage.error('广播消息失败')
      } finally {
        broadcasting.value = false
      }
    }

    const handleViewMessage = async (row) => {
      try {
        const response = await getSystemMessageById(row.id)
        if (response.code === 200) {
          currentMessage.value = response.data
          messageDetailDialogVisible.value = true
        }
      } catch (error) {
        console.error('获取消息详情失败:', error)
        ElMessage.error('获取消息详情失败')
      }
    }

    const handleEditMessage = async (row) => {
      try {
        const response = await getSystemMessageById(row.id)
        if (response.code === 200) {
          const messageData = response.data
          Object.assign(messageForm, {
            id: messageData.id,
            title: messageData.title,
            messageType: messageData.messageType,
            content: messageData.content,
            targetType: messageData.targetType,
            roleId: messageData.roleId || '',
            userIds: messageData.userIds || [],
            priority: messageData.priority,
            isScheduled: !!messageData.scheduledTime,
            scheduledTime: messageData.scheduledTime || null
          })
          isEdit.value = true
          sendMessageDialogVisible.value = true
        }
      } catch (error) {
        console.error('获取消息详情失败:', error)
        ElMessage.error('获取消息详情失败')
      }
    }

    const handleDeleteMessage = (row) => {
      ElMessageBox.confirm(
        `确定要删除消息"${row.title}"吗？此操作不可恢复。`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await deleteSystemMessage(row.id)
          if (response.code === 200) {
            ElMessage.success('删除成功')
            loadMessageList()
            loadStatistics()
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除消息失败:', error)
          ElMessage.error('删除消息失败')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }

    const handleBatchDelete = () => {
      if (!selectedMessages.value.length) {
        ElMessage.warning('请选择要删除的消息')
        return
      }

      ElMessageBox.confirm(
        `确定要删除选中的 ${selectedMessages.value.length} 条消息吗？此操作不可恢复。`,
        '确认批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const messageIds = selectedMessages.value.map(item => item.id)
          const response = await batchDeleteMessages(messageIds)
          if (response.code === 200) {
            ElMessage.success('批量删除成功')
            selectedMessages.value = []
            loadMessageList()
            loadStatistics()
          } else {
            ElMessage.error(response.message || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }

    const handleExport = () => {
      // 导出功能实现
      ElMessage.info('导出功能开发中...')
    }

    // 辅助方法
    const getMessageTypeLabel = (type) => {
      const typeMap = {
        notification: '通知',
        announcement: '公告',
        reminder: '提醒',
        warning: '警告',
        urgent: '紧急'
      }
      return typeMap[type] || type
    }

    const getMessageTypeTagType = (type) => {
      const typeMap = {
        notification: '',
        announcement: 'success',
        reminder: 'warning',
        warning: 'danger',
        urgent: 'danger'
      }
      return typeMap[type] || ''
    }

    const getTargetTypeLabel = (type) => {
      const typeMap = {
        all: '所有用户',
        role: '指定角色',
        user: '指定用户'
      }
      return typeMap[type] || type
    }

    const getStatusLabel = (status) => {
      const statusMap = {
        sent: '已发送',
        pending: '待发送',
        failed: '发送失败',
        scheduled: '定时发送'
      }
      return statusMap[status] || status
    }

    const getStatusTagType = (status) => {
      const statusMap = {
        sent: 'success',
        pending: 'warning',
        failed: 'danger',
        scheduled: 'info'
      }
      return statusMap[status] || ''
    }

    const getPriorityLabel = (priority) => {
      const priorityMap = {
        low: '低',
        medium: '中',
        high: '高',
        urgent: '紧急'
      }
      return priorityMap[priority] || priority
    }

    const getPriorityTagType = (priority) => {
      const priorityMap = {
        low: 'info',
        medium: '',
        high: 'warning',
        urgent: 'danger'
      }
      return priorityMap[priority] || ''
    }

    return {
      // 响应式数据
      loading,
      sending,
      broadcasting,
      messageList,
      selectedMessages,
      userList,
      statistics,
      pagination,
      searchForm,
      messageForm,
      broadcastForm,
      currentMessage,
      sendMessageDialogVisible,
      broadcastDialogVisible,
      messageDetailDialogVisible,
      isEdit,
      hasSelection,

      // WebSocket 相关数据
      wsConnected,

      // 表单引用
      searchFormRef,
      messageFormRef,
      broadcastFormRef,

      // 表单验证规则
      messageFormRules,
      broadcastFormRules,

      // 方法
      loadMessageList,
      loadStatistics,
      handleSearch,
      handleResetSearch,
      handleRefresh,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      showSendMessageDialog,
      showBroadcastDialog,
      handleDialogClose,
      handleBroadcastDialogClose,
      handleTargetTypeChange,
      handleSendMessage,
      handleBroadcastMessage,
      handleViewMessage,
      handleEditMessage,
      handleDeleteMessage,
      handleBatchDelete,
      handleExport,

      // 辅助方法
      getMessageTypeLabel,
      getMessageTypeTagType,
      getTargetTypeLabel,
      getStatusLabel,
      getStatusTagType,
      getPriorityLabel,
      getPriorityTagType
    }
  }
}
</script>

<style lang="scss" scoped>
.system-message {
  padding: 20px;

  .breadcrumb {
    margin-bottom: 20px;
  }

  .ws-status-indicator {
    position: fixed;
    top: 80px;
    right: 30px;
    z-index: 1000;

    .status-dot {
      display: flex;
      align-items: center;
      padding: 8px 16px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      cursor: pointer;

      &.connected {
        background-color: #f0f9ff;
        color: #1890ff;
        border: 1px solid #91d5ff;

        &::before {
          content: '';
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #52c41a;
          margin-right: 8px;
          animation: pulse 2s infinite;
        }
      }

      &.disconnected {
        background-color: #fff2f0;
        color: #ff4d4f;
        border: 1px solid #ffccc7;

        &::before {
          content: '';
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #ff4d4f;
          margin-right: 8px;
        }
      }

      .status-text {
        white-space: nowrap;
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
  }

  @keyframes pulse {
    0% {
      box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.7);
    }
    70% {
      box-shadow: 0 0 0 10px rgba(82, 196, 26, 0);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
    }
  }

  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      .stat-item {
        display: flex;
        align-items: center;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          .el-icon {
            font-size: 28px;
            color: white;
          }
        }

        .stat-content {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }
    }
  }

  .operation-card {
    margin-bottom: 20px;

    .operation-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .left-buttons,
      .right-buttons {
        display: flex;
        gap: 10px;
      }
    }

    .search-form {
      border-top: 1px solid #ebeef5;
      padding-top: 15px;
    }
  }

  .table-card {
    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }

  .message-detail {
    .message-content {
      white-space: pre-wrap;
      line-height: 1.6;
      max-height: 200px;
      overflow-y: auto;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .system-message {
    padding: 10px;

    .ws-status-indicator {
      top: 70px;
      right: 15px;

      .status-dot {
        padding: 6px 12px;
        font-size: 11px;
      }
    }

    .statistics-cards {
      .el-col {
        margin-bottom: 10px;
      }
    }

    .operation-bar {
      flex-direction: column;
      gap: 15px;

      .left-buttons,
      .right-buttons {
        width: 100%;
        justify-content: center;
      }
    }

    .search-form {
      .el-form-item {
        margin-bottom: 10px;
      }
    }
  }
}
</style>